package com.servlet;

import com.bean.Teacher;
import com.google.gson.Gson;
import com.service.TeacherService;
import com.service.impl.TeacherServiceImpl;
import com.utils.Page;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.utils.Page.PAGE_SIZE;

@WebServlet(name = "TeacherServlet", urlPatterns = "/TeacherServlet.do")
public class TeacherServlet extends BaseServlet {
    TeacherService teacherService = new TeacherServiceImpl();

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        String content = request.getParameter("content");
        Page<Teacher> page = teacherService.page(pageNo, pageSize, content);
        Map map = new LinkedHashMap();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }
    protected void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Teacher teacher = new Teacher();
        WebUtils.copyParamToBean(request.getParameterMap(), teacher);
        teacher.setId(null);
        int tip = teacherService.insert(teacher);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }
    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int tip = teacherService.deleteById(id);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Teacher teacher = new Teacher();
        WebUtils.copyParamToBean(request.getParameterMap(), teacher);
        int tip = teacherService.updeteInfo(teacher);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }
}
